<script setup lang="ts">
import { reactive, ref, nextTick, computed, watch } from 'vue';
import { getAppGroupTreeList, searchPagesByPage, publishPage, deletePage, movePage } from '@code/api/code/page';
import { selectGroupById } from '@code/api/application';
import { resetFormPlus, downloadUrl } from '@/utils/zmids';
import { ElMessage, ElMessageBox } from 'element-plus';
import defaultSettings from '@/settings';
import type { FormInstance } from 'element-plus';
import { getPinyin } from '@/api/common';
import { useRouter, useRoute } from 'vue-router';
import { getToken } from '@/utils/auth';
import { useCodeStore } from '@code/store';

defineProps({
  // 是否作为弹框内选择页面
  inDialog: {
    type: Boolean,
    default: false
  }
});

defineOptions({
  name: 'PageInfo'
});

const emits = defineEmits(['select']);

const isPageInfoRefresh = computed(() => {
  const codeStore = useCodeStore();
  return codeStore.getIsPageInfoRefresh;
});

watch(
  () => isPageInfoRefresh.value,
  (v: Boolean) => {
    if (v) {
      getPageList();
      const codeStore = useCodeStore();
      codeStore.setIsPageInfoRefresh(false);
    }
  }
);

const { push } = useRouter();

const queryParams = reactive({
  pagNum: 1,
  pageSize: 10,
  pageNameLike: '',
  pageType: ''
});

// 页面管理迁入参数
const move = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '页面移动'
});

const moveParams = reactive({
  pageId: '',
  appId: '',
  groupId: ''
});

const showSearch = ref<Boolean>(true);

const total = ref<Number>(0);

const queryForm = ref<FormInstance>();

const appList = ref([]);

const pageList = ref([]);

// 默认展开的节点数组
const defaultExpendList = ref<Array<String>>([]);

const defaultProps = {
  label: 'name',
  children: 'children'
};

const pageTypes = [
  {
    label: '填报表单',
    value: 'F'
  },
  {
    label: '查询表单',
    value: 'Q'
  },
  {
    label: '模型表单',
    value: 'M'
  }
];

const tree = ref([]);

const curGroupId = ref('');

const curAppId = ref('');

// 页面管理迁入参数
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { [defaultSettings.tokenName]: 'Bearer ' + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/code/page/info/importZip'
});

const uploadRef = ref();

const uploadParams = reactive({
  get groupId() {
    return curGroupId.value;
  },
  get appId() {
    return curAppId.value;
  }
});

const getAppList = async () => {
  return getAppGroupTreeList().then((res) => {
    appList.value = res.data;
    defaultExpendList.value = appList.value.map((p: any) => p.id);
  });
};

const getPageList = async () => {
  const params = {
    ...queryParams,
    groupId: curGroupId.value
  };
  return searchPagesByPage(params).then((res) => {
    pageList.value = res.data.list;
    total.value = res.data.total;
  });
};

const init = async () => {
  getAppList();
  getPageList();
};

const handleQuery = () => {
  getPageList();
};

const resetQuery = () => {
  resetFormPlus(queryForm.value);
  handleQuery();
};

const handleNodeClick = async (node) => {
  // 第一层都是应用，第二层开始才是分类
  if (node.iconSkin == 'app') {
    return;
  }
  curGroupId.value = node.id;
  const detail = await getGroupDetail(curGroupId.value);
  curAppId.value = detail.groupAppId;
  getPageList();
};

// 用于查询分组对应的appid
const getGroupDetail = async (id: string): Promise<any> => {
  const res = await selectGroupById(id);

  return res.data;
};

const handleAdd = (row: any) => {
  if (!curGroupId.value) {
    ElMessage.warning('必须先选中一个分类！');
    return;
  }
  push({
    name: 'PageEdit',
    query: {
      type: 'add',
      groupId: curGroupId.value,
      appId: curAppId.value
    }
  });
};

const handleApply = (row?: any) => {
  publishPage(row.pageVersionId).then((res) => {
    if (res) {
      ElMessage.success('发布成功');
      getPageList();
    }
  });
};

const handleDelete = (row?: any) => {
  deletePage(row.pageId).then((res) => {
    if (res) {
      ElMessage.success('删除成功');
      getPageList();
    }
  });
};

const handleUpdate = (row: any, step: number) => {
  push({
    name: 'PageEdit',
    query: {
      type: 'edit',
      groupId: curGroupId.value,
      appId: curAppId.value,
      id: row.pageVersionId,
      pageId: row.pageId,
      step: step
    }
  });
};

const handleFilling = (row: any) => {
  push({ name: 'PageFilling', params: { pageId: row.pageId } });
};

const handleSelect = (row: any) => {
  emits('select', row.pageId);
};

// 迁出
const handleExport = (row: any) => {
  downloadUrl('/code/page/info/exportZip/' + row.pageId, undefined);
};

// 迁入
const handleImport = () => {
  upload.title = '页面管理迁入';
  upload.open = true;
};

// 上传中回调
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};

// 上传完成后回调
const handleFileSuccess = (response, file, fileList) => {
  cancelUpload();
  ElMessageBox.alert(response.msg, '迁入结果', { dangerouslyUseHTMLString: true });
  getPageList();
};

// 提交上传
const submitFileForm = () => {
  if (!curGroupId.value) {
    ElMessage.error('请选择分组！');
    return;
  }
  uploadRef.value.submit();
};

// 取消上传
const cancelUpload = () => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value.clearFiles();
};

// 复制
const handleCopy = (row: any, step: number) => {
  push({
    name: 'PageEdit',
    query: {
      type: 'copy',
      groupId: curGroupId.value,
      appId: curAppId.value,
      id: row.pageVersionId,
      pageId: row.pageId,
      step: step
    }
  });
};

// 移动
const handleMove = (row: any) => {
  moveParams.pageId = row.pageId;
  move.open = true;
};

const submitMoveForm = async () => {
  if (!moveParams.groupId) {
    ElMessage.error('请选择分组！');
    return;
  }
  const detail = await getGroupDetail(moveParams.groupId);
  if (!detail) {
    ElMessage.error('请选择一个具体的分组，而不是应用！');
    return;
  }
  moveParams.appId = detail.groupAppId;
  movePage(moveParams).then((res) => {
    if (res.code == '200') {
      ElMessage.success('移动成功，您可在相关列表中查看详情！');
      handleQuery();
      cancelMove();
    } else {
      ElMessage.error('移动失败，请联系管理员解决！');
    }
  });
};

const cancelMove = () => {
  move.open = false;
  moveParams.pageId = '';
  moveParams.appId = '';
  moveParams.groupId = '';
};

init();
</script>

<template>
  <div class="app-container">
    <el-row>
      <el-col :span="4">
        <el-tree
          :data="appList"
          :props="defaultProps"
          :expand-on-click-node="false"
          node-key="id"
          ref="tree"
          highlight-current
          :default-expanded-keys="defaultExpendList"
          @node-click="handleNodeClick"
        />
      </el-col>
      <el-col :span="20">
        <div>
          <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="页面名称" prop="pageNameLike">
              <el-input v-model="queryParams.pageNameLike" placeholder="请输入页面名称" clearable size="default" style="width: 240px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="页面类型" prop="pageType">
              <el-select v-model="queryParams.pageType" style="width: 240px">
                <el-option v-for="(opt, index) in pageTypes" :key="index" :value="opt.value" :label="opt.label" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <search-button @click="handleQuery" />
              <reset-button @click="resetQuery" />
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <add-button @click="handleAdd" />
            <import-button @click="handleImport" text="迁入" />
            <right-toolbar v-model:showSearch="showSearch" @query-table="getPageList" />
          </el-row>
          <el-table :data="pageList">
            <el-table-column prop="pageId" label="页面ID" align="center" width="270" />
            <el-table-column prop="pageName" label="页面名称" />
            <el-table-column prop="pageCode" label="页面编码" />
            <el-table-column prop="pageType" label="页面类型" align="center" width="160">
              <template #default="scope">
                {{ pageTypes.find((type) => type.value == scope.row.pageType).label }}
              </template>
            </el-table-column>
            <el-table-column prop="version" label="版本号" align="center" width="80" />
            <el-table-column prop="isPublish" label="发布状态" align="center" width="80">
              <template #default="scope">
                <three-choices-tag
                  :value="scope.row.version !== '1' && scope.row.isPublish === 'N' ? 'YN' : scope.row.isPublish"
                  c1Value="Y"
                  c1Text="已发布"
                  c2Value="YN"
                  c2Text="有更新"
                  c2Type="primary"
                  c3Value="N"
                  c3Text="未发布"
                ></three-choices-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="340">
              <template #default="scope">
                <text-download-button @click="handleExport(scope.row)" text="迁出" />
                <text-copy-button @click="handleCopy(scope.row, 0)" text="复制" />
                <text-edit-button @click="handleMove(scope.row)" text="移动" />
                <template v-if="inDialog">
                  <text-add-button @click="handleSelect(scope.row)" text="选择" />
                </template>
                <template v-else>
                  <text-add-button @click="handleApply(scope.row)" v-if="scope.row.isPublish == 'N'" text="发布" />
                  <text-edit-button @click="handleFilling(scope.row)" v-if="!(scope.row.version == 1 && scope.row.isPublish == 'N')" text="填报" />
                  <text-edit-button @click="handleUpdate(scope.row, 0)" />
                  <text-edit-button v-if="scope.row.isPublish === 'N'" text="表单设计" @click="handleUpdate(scope.row, 1)" />
                  <text-delete-button @click="handleDelete(scope.row)" :title="'是否确认删除' + scope.row.pageName + '?'" />
                </template>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getPageList" />
        </div>
      </el-col>
    </el-row>
    <!-- 页面管理迁入对话框 -->
    <drag-dialog :title="upload.title" :close-on-click-modal="false" v-model="upload.open" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".zip"
        :headers="upload.headers"
        :action="upload.url"
        :data="uploadParams"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            Tips：迁入迁出主要用于多环境间数据传递，因此不建议用户对迁出的包进行修改
            <div class="el-upload__tip" style="color: red"> 提示：仅允许上传“zip”格式文件！ </div>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <dialog-footer @ok="submitFileForm" @cancel="cancelUpload" />
      </template>
    </drag-dialog>
    <drag-dialog :title="move.title" :close-on-click-modal="false" v-model="move.open" width="400px" append-to-body>
      <el-tree-select
        v-model="moveParams.groupId"
        :data="appList"
        check-strictly
        :render-after-expand="false"
        :props="{
          value: 'id',
          label: 'title',
          children: 'children'
        }"
        placeholder="请选择分组"
        clearable
      />
      <template #footer>
        <dialog-footer @ok="submitMoveForm" @cancel="cancelMove" />
      </template>
    </drag-dialog>
  </div>
</template>
